<?php
global $_W, $_GPC;
$weid = $this->_weid;
$setting = $this->getSetting();
load()->func('tpl');
$action = 'order';
$title = $this->actions_titles[$action];
$storeid = intval($_GPC['storeid']);
$returnid = $this->checkPermission($storeid);
$GLOBALS['frames'] = $this->getMainMenu();

if ($this->checkTrade()==0) {
    $_GPC['idArr']  = '';
}

$operation = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
if ($operation == 'display') {

    $commoncondition = " weid = '{$_W['uniacid']}' ";
    if ($storeid != 0) {
        $commoncondition .= " AND storeid={$storeid} ";
    }

    $commonconditioncount = " weid = '{$_W['uniacid']}' ";
    if ($storeid != 0) {
        $commonconditioncount .= " AND storeid={$storeid} ";
    }

    if (!empty($_GPC['time'])) {
        $starttime = strtotime($_GPC['time']['start']);
        $endtime = strtotime($_GPC['time']['end']) + 86399;
        $commoncondition .= " AND dateline >= :starttime AND dateline <= :endtime ";
        $paras[':starttime'] = $starttime;
        $paras[':endtime'] = $endtime;
    }

    if (empty($starttime) || empty($endtime)) {
        $starttime = strtotime('-1 month');
        $endtime = time();
    }

    $pindex = max(1, intval($_GPC['page']));
    $psize = 10;

    if (!empty($_GPC['ordersn'])) {
        $commoncondition .= " AND ordersn LIKE '%{$_GPC['ordersn']}%' ";
    }
    if (!empty($_GPC['dining_mode'])) {
        $commoncondition .= " AND dining_mode = '" . intval($_GPC['dining_mode']) . "' ";
    }
    $tablesid = $_GPC['tableid'];
    $table = pdo_fetch("SELECT * FROM " . tablename($this->table_tables) . " where weid = :weid AND title=:title LIMIT 1", array(':weid' => $weid, ':title' => $tablesid));
    if (!empty($table)) {
        $commoncondition .= " AND tables = '" . $table['id'] . "' ";
    }

    if (isset($_GPC['status']) && $_GPC['status'] != '') {
        $commoncondition .= " AND status = '" . intval($_GPC['status']) . "'";
    }

    if (isset($_GPC['paytype']) && $_GPC['paytype'] != '') {
        $commoncondition .= " AND paytype = '" . intval($_GPC['paytype']) . "' ";
    }

    if ($_GPC['out_put'] == 'output') {
        $sql = "select * from " . tablename($this->table_order)
            . " WHERE $commoncondition ORDER BY status DESC, dateline DESC ";
        $list = pdo_fetchall($sql, $paras);
        $orderstatus = array(
            '-1' => array('css' => 'default', 'name' => '已取消'),
            '0' => array('css' => 'danger', 'name' => '待处理'),
            '1' => array('css' => 'info', 'name' => '已确认'),
            '2' => array('css' => 'warning', 'name' => '已付款'),
            '3' => array('css' => 'success', 'name' => '已完成')
        );

        $paytypes = array(
            '0' => array('css' => 'danger', 'name' => '未支付'),
            '1' => array('css' => 'info', 'name' => '余额支付'),
            '2' => array('css' => 'warning', 'name' => '微信支付'),
            '3' => array('css' => 'success', 'name' => '现金支付'),
            '4' => array('css' => 'warning', 'name' => '支付宝')
        );

        $i = 0;
        foreach ($list as $key => $value) {
            $arr[$i]['ordersn'] = "'".$value['ordersn'];
            $arr[$i]['transid'] = "'".$value['transid'];
            $arr[$i]['paytype'] = $paytypes[$value['paytype']]['name'];
            $arr[$i]['status'] = $orderstatus[$value['status']]['name'];
            $arr[$i]['totalprice'] = $value['totalprice'];
            $arr[$i]['username'] = $value['username'];
            $arr[$i]['tel'] = $value['tel'];
            $arr[$i]['address'] = $value['address'];
            $arr[$i]['dateline'] = date('Y-m-d H:i:s', $value['dateline']);
            $i++;
        }

        $this->exportexcel($arr, array('订单号', '商户订单号', '支付方式', '状态', '总价', '真实姓名', '电话号码', '地址', '时间'), time());
        exit();
    }

    $list = pdo_fetchall("SELECT * FROM " . tablename($this->table_order) . " WHERE $commoncondition ORDER BY id desc, dateline DESC LIMIT " . ($pindex - 1) * $psize . ',' . $psize, $paras);

    $order_count = pdo_fetchcolumn("SELECT COUNT(1) FROM " . tablename($this->table_order) . " WHERE weid=:weid AND status=0 LIMIT 1", array(':weid' => $this->_weid));

    $total = pdo_fetchcolumn('SELECT COUNT(1) FROM ' . tablename($this->table_order) . " WHERE $commoncondition", $paras);
    $pager = pagination($total, $pindex, $psize);

    if (!empty($list)) {
        foreach ($list as $key => $value) {
            $userids[$row['from_user']] = $row['from_user'];
            if ($value['dining_mode'] == 1) {
                $tablesid = intval($value['tables']);
                $table = pdo_fetch("SELECT * FROM " . tablename($this->table_tables) . " where id=:id LIMIT 1", array(':id' => $tablesid));
                if (!empty($table)) {
                    $table_title = $table['title'];
                    $list[$key]['table'] = $table_title;
                }
            }
        }
    }

    //打印数量
    $print_order_count = pdo_fetchall("SELECT orderid,COUNT(1) as count FROM " . tablename($this->table_print_order) . "  GROUP BY orderid,weid having weid = :weid", array(':weid' => $_W['uniacid']), 'orderid');

    //门店列表
    $storelist = pdo_fetchall("SELECT * FROM " . tablename($this->table_stores) . " WHERE weid = :weid", array(':weid' => $_W['uniacid']), 'id');

} elseif ($operation == 'detail') {
    //流程 第一步确认付款 第二步确认订单 第三步，完成订单
    $id = intval($_GPC['id']);
    $order = $this->getOrderById($id);
    $fans = $this->getFansByOpenid($order['from_user']);

    if (!empty($_GPC['confirmprice'])) {
        pdo_update($this->table_order,
            array(
                'totalprice' => $_GPC['updateprice'],
                'paydetail' => empty($order['paydetail']) ? date('Y-m-d H:i', TIMESTAMP) . '改价为' . $_GPC['updateprice'] : $order['paydetail'] . '<br/>' . date('Y-m-d H:i', TIMESTAMP) . '改价为' . $_GPC['updateprice']
            ),
            array('id' => $id)
        );
        $paylog = pdo_fetch("SELECT * FROM " . tablename('core_paylog') . " WHERE tid=:tid AND uniacid=:uniacid AND status=0 AND module='weisrc_dish'
ORDER BY plid
DESC LIMIT 1", array(':tid' => $id, ':uniacid' => $this->_weid));
        if (!empty($paylog)) {
            pdo_update('core_paylog', array('fee' => $_GPC['updateprice']), array('plid' => $paylog['plid']));
        }
        message('改价成功！', referer(), 'success');
    }

    if (checksubmit('confrimsign')) {
        pdo_update($this->table_order, array('reply' => $_GPC['reply']), array('id' => $id));
        message('操作成功！', referer(), 'success');
    }

    $store = pdo_fetch("SELECT * FROM " . tablename($this->table_stores) . " WHERE id=:id AND weid=:weid LIMIT 1", array(':id' => $order['storeid'], ':weid' => $weid));
    if (!empty($_GPC['finish'])) {
        //isfinish
        if ($order['isfinish'] == 0) {
            //计算积分
            $this->setOrderCredit($order['id']);
            pdo_update($this->table_order, array('isfinish' => 1), array('id' => $id));
            pdo_update($this->table_fans, array('paytime' => TIMESTAMP), array('id' => $fans['id']));
            if ($order['dining_mode'] == 1) {
                pdo_update($this->table_tables, array('status' => 0), array('id' => $order['tables']));
            }
            $this->set_commission($id);
        }
        pdo_update($this->table_order, array('status' => 3), array('id' => $id, 'weid' => $weid));
        $this->updateFansData($order['from_user']);
        $this->updateFansFirstStore($order['from_user'], $order['storeid']);
        $order = $this->getOrderById($id);
        $this->sendOrderNotice($order, $store, $setting);
        message('订单操作成功！', referer(), 'success');
    }
    if (!empty($_GPC['cancel'])) {
        pdo_update($this->table_order, array('status' => 1), array('id' => $id, 'weid' => $weid));
        message('取消完成订单操作成功！', referer(), 'success');
    }
    if (!empty($_GPC['confirm'])) {
        pdo_update($this->table_order, array('status' => 1), array('id' => $id, 'weid' => $weid));

        $order = $this->getOrderById($id);
        $this->sendOrderNotice($order, $store, $setting);
        message('确认订单操作成功！', referer(), 'success');
    }
    if (!empty($_GPC['cancelpay'])) {
        pdo_update($this->table_order, array('status' => 0), array('id' => $id, 'weid' => $weid));
        message('取消订单付款操作成功！', referer(), 'success');
    }
    if (!empty($_GPC['confrimpay'])) {
        pdo_update($this->table_order, array('ispay' => 1), array('id' => $id, 'weid' => $weid));
        $order = $this->getOrderById($id);
        $this->sendOrderNotice($order, $store, $setting);
        message('确认订单付款操作成功！', referer(), 'success');
    }
    if (!empty($_GPC['close'])) {
        if ($order['ispay'] == 1) {
            $coin = floatval($order['totalprice']);
            if ($order['paytype'] == 1) {
                $this->setFansCoin($order['from_user'], $coin, "码上点餐单号{$order['ordersn']}退款");
            }
        }
        pdo_update($this->table_order, array('status' => -1), array('id' => $id, 'weid' => $weid));
        $order = $this->getOrderById($id);
        $this->sendOrderNotice($order, $store, $setting);
        message('订单关闭操作成功！', referer(), 'success');
    }
    if (!empty($_GPC['open'])) {
        pdo_update($this->table_order, array('status' => 0), array('id' => $id, 'weid' => $weid));
        message('开启订单操作成功！', referer(), 'success');
    }

    $item = pdo_fetch("SELECT * FROM " . tablename($this->table_order) . " WHERE id = :id", array(':id' => $id));

    $goods = pdo_fetchall("SELECT a.goodsid,a.price, a.total,b.thumb,b.title,b.id,b.credit FROM " . tablename($this->table_order_goods) . " a INNER JOIN " . tablename($this->table_goods) . " b ON a.goodsid=b.id WHERE a.orderid = :id", array(':id' => $id));
    if ($item['dining_mode'] == 1) {
        $tablesid = intval($item['tables']);
        $table = pdo_fetch("SELECT * FROM " . tablename($this->table_tables) . " where weid = :weid AND id=:id LIMIT 1", array(':weid' => $weid, ':id' => $tablesid));
        if (empty($table)) {
//                    exit('餐桌不存在！');
        } else {
            $tablezones = pdo_fetch("SELECT * FROM " . tablename($this->table_tablezones) . " where weid = :weid AND id=:id LIMIT 1", array(':weid' => $weid, ':id' => $table['tablezonesid']));
            if (empty($tablezones)) {
//                        exit('餐桌类型不存在！');
            }
            $table_title = $tablezones['title'] . '-' . $table['title'];
        }
    }
    if ($item['dining_mode'] == 3) {
        $tablezones = pdo_fetch("SELECT * FROM " . tablename($this->table_tablezones) . " where weid = :weid AND id=:id LIMIT 1", array(':weid' => $weid, ':id' => $item['tablezonesid']));
    }
    if ($item['couponid'] != 0) {
        $coupon = pdo_fetch("SELECT a.* FROM " . tablename($this->table_coupon) . "
        a INNER JOIN " . tablename($this->table_sncode) . " b ON a.id=b.couponid
 WHERE a.weid = :weid AND b.id=:couponid ORDER BY b.id
 DESC LIMIT 1", array(':weid' => $weid, ':couponid' => $item['couponid']));
        if (!empty($coupon)) {
            if ($coupon['type'] == 2) {
                $coupon_info = "抵用金额" . $coupon['dmoney'];
            } else {
                $coupon_info = $coupon['title'];
            }
        }
    }
} else if ($operation == 'delete') {
    $id = $_GPC['id'];
    pdo_delete($this->table_order, array('id' => $id, 'weid' => $weid));
    pdo_delete($this->table_order_goods, array('orderid' => $id, 'weid' => $weid));
    message('删除成功！', $this->createWebUrl('order', array('op' => 'display', 'storeid' => $storeid)), 'success');
} else if ($operation == 'print') {
    $id = $_GPC['id'];//订单id
    $order = $this->getOrderById($id);
    $flag = false;

    $prints = pdo_fetchall("SELECT * FROM " . tablename($this->table_print_setting) . " WHERE weid = :weid AND storeid=:storeid", array(':weid' => $weid, ':storeid' => $order['storeid']));

    if (empty($prints)) {
        message('请先添加打印机或者开启打印机！');
    }

    foreach ($prints as $key => $value) {
        if ($value['print_status'] == 1 && $value['type'] == 'hongxin') {
            $data = array(
                'weid' => $_W['uniacid'],
                'orderid' => $id,
                'print_usr' => $value['print_usr'],
                'print_status' => -1,
                'dateline' => TIMESTAMP
            );
            pdo_insert('weisrc_dish_print_order', $data);
        }
    }
    $this->feieSendFreeMessage($id);
    $this->feiyinSendFreeMessage($id);
    $this->_365SendFreeMessage($id);
    $this->_yilianyunSendFreeMessage($id);
    message('操作成功！', $this->createWebUrl('order', array('op' => 'display', 'storeid' => $order['storeid'])), 'success');
} elseif ($operation == 'printall') {
    $rowcount = 0;
    $notrowcount = 0;
    foreach ($_GPC['idArr'] as $k => $id) {
        $id = intval($id);
        if (!empty($id)) {
            $order = $this->getOrderById($id);
            $prints = pdo_fetchall("SELECT * FROM " . tablename($this->table_print_setting) . " WHERE weid = :weid AND storeid=:storeid", array(':weid' => $weid, ':storeid' => $order['storeid']));

            if (empty($prints)) {
                $notrowcount++;
                continue;
            }
            if ($order['ispay'] == 0) {
                $notrowcount++;
                continue;
            }
            foreach ($prints as $key => $value) {
                if ($value['print_status'] == 1 && $value['type'] == 'hongxin') {
                    $data = array(
                        'weid' => $weid,
                        'orderid' => $id,
                        'print_usr' => $value['print_usr'],
                        'print_status' => -1,
                        'dateline' => TIMESTAMP
                    );
                    pdo_insert($this->table_print_order, $data);
                }
            }
            $this->feieSendFreeMessage($id);
            $this->feiyinSendFreeMessage($id);
            $this->_365SendFreeMessage($id);
            $this->_yilianyunSendFreeMessage($id);
            $rowcount++;
        }
    }
    $this->message("操作成功！共打印{$rowcount}条数据,{$notrowcount}条数据未打印!", '', 0);
} elseif ($operation == 'payall') {
    $rowcount = 0;
    $notrowcount = 0;
    foreach ($_GPC['idArr'] as $k => $id) {
        $id = intval($id);
        if (!empty($id)) {
            $order = $this->getOrderById($id);
            if ($order) {
                pdo_update($this->table_order, array('ispay' => 1), array('id' => $id, 'weid' => $weid));
                $rowcount++;
            }
        }
    }
    $this->message("操作成功,共操作{$rowcount}条数据!", '', 0);
}
elseif ($operation == 'confirmall') {
    $rowcount = 0;
    $notrowcount = 0;
    foreach ($_GPC['idArr'] as $k => $id) {
        $id = intval($id);
        if (!empty($id)) {
            $order = $this->getOrderById($id);
            if ($order) {
                pdo_update($this->table_order, array('status' => 1), array('id' => $id, 'weid' => $weid));
                $rowcount++;
            }
        }
    }
    $this->message("操作成功,共操作{$rowcount}条数据!", '', 0);
} elseif ($operation == 'cancelall') {
    $rowcount = 0;
    $notrowcount = 0;
    foreach ($_GPC['idArr'] as $k => $id) {
        $id = intval($id);
        if (!empty($id)) {
            $order = $this->getOrderById($id);
            if ($order) {
                if ($order['ispay'] == 1) {
                    $coin = floatval($order['totalprice']);
                    if ($order['paytype'] == 1) {
                        $this->setFansCoin($order['from_user'], $coin, "码上点餐单号{$order['ordersn']}退款");
                    }
                }
                pdo_update($this->table_order, array('status' => -1), array('id' => $id, 'weid' => $weid));
                $order = $this->getOrderById($id);
                $this->sendOrderNotice($order, $store, $setting);
                $rowcount++;
            }
        }
    }
    $this->message("操作成功,共操作{$rowcount}条数据!", '', 0);
} elseif ($operation == 'finishall') {
    $rowcount = 0;
    $notrowcount = 0;
    foreach ($_GPC['idArr'] as $k => $id) {
        $id = intval($id);
        if (!empty($id)) {
            $order = $this->getOrderById($id);
            if ($order) {
                if ($order['isfinish'] == 0) {
                    //计算积分
                    $this->setOrderCredit($order['id']);
                    pdo_update($this->table_order, array('isfinish' => 1), array('id' => $id));
                    pdo_update($this->table_fans, array('paytime' => TIMESTAMP), array('id' => $fans['id']));
                    if ($order['dining_mode'] == 1) {
                        pdo_update($this->table_tables, array('status' => 0), array('id' => $order['tables']));
                    }
                    $this->set_commission($id);
                }
                pdo_update($this->table_order, array('status' => 3), array('id' => $id, 'weid' => $weid));
                $this->updateFansData($order['from_user']);
                $this->updateFansFirstStore($order['from_user'], $order['storeid']);
                $order = $this->getOrderById($id);
                $store = $this->getStoreById($order['storeid']);
                $this->sendOrderNotice($order, $store, $setting);
                $rowcount++;
            }
        }
    }
    $this->message("操作成功,共操作{$rowcount}条数据!", '', 0);
} elseif ($operation == 'noticeall') {
    $rowcount = 0;
    $notrowcount = 0;
    foreach ($_GPC['idArr'] as $k => $id) {
        $id = intval($id);
        if (!empty($id)) {
            $order = $this->getOrderById($id);
            if ($order) {
                $this->sendOrderNotice($order, $store, $setting);
                $rowcount++;
            }
        }
    }
    $this->message("操作成功,共操作{$rowcount}条数据!", '', 0);
}

include $this->template('web/allorder');